package com.example.smartcity_poverty.ui.AllService.Attorneys.activity.AttMe.activity

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import androidx.recyclerview.widget.GridLayoutManager
import com.example.smartcity_poverty.App
import com.example.smartcity_poverty.App.Companion.getToken
import com.example.smartcity_poverty.Base.BaseRecyclerAdapter
import com.example.smartcity_poverty.R
import com.example.smartcity_poverty.logic.Repository
import com.example.smartcity_poverty.logic.Repository.api
import com.example.smartcity_poverty.logic.Repository.coroutine
import com.example.smartcity_poverty.logic.model.Attreneys.AttMoreModel
import com.example.smartcity_poverty.logic.util.Util
import com.example.smartcity_poverty.logic.util.Util.show
import com.example.smartcity_poverty.ui.AllService.Attorneys.activity.AttShowListAllActivity
import kotlinx.android.synthetic.main.activity_att_me_add.*
import kotlinx.android.synthetic.main.activity_att_show_list_all.*
import kotlinx.android.synthetic.main.activity_attorneys_show.*
import kotlinx.android.synthetic.main.activity_attorneys_show.attListShowImage
import kotlinx.android.synthetic.main.re_att_more.*
import kotlinx.coroutines.Dispatchers
import okhttp3.MediaType
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.RequestBody.Companion.toRequestBody
import org.json.JSONObject

/**
 * 咨询页
 */
class AttMeAddActivity : AppCompatActivity() {

    var idd = 0

    var lvShiId = 0
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
        setContentView(R.layout.activity_att_me_add)
        title = "咨询"

        val id = intent.getStringExtra("id")?.toInt()
        lvShiId = id!!

        coroutine(Dispatchers.IO){
            setUserAll(id)
            setOverride()
        }


        // 点击展开列表哦选择
        attMeAddBtnMore.setOnClickListener {
            runOnUiThread {
                attMeAddMoreLayout.visibility = View.VISIBLE
            }
        }

        attMeAddBtnOk.setOnClickListener {
            coroutine(Dispatchers.IO){
                attMeAdd()
            }
        }

    }


    /**
     * 提交按钮
     */
    private suspend fun attMeAdd(){
        if (attMeAddBtnMore.text.toString() == "问题类型"){
            runOnUiThread { "你还没有选择类型".show() }
        }else {
            if (attMeAddContent.text.toString().isNotEmpty() && attMeAddPhone.text.toString().isNotEmpty()){

                api.getAttSetAll(getToken(), JSONObject().apply {
                    put("lawyerId", lvShiId)
                    put("legalExpertiseId", idd)
                    put("content", attMeAddContent.text.toString())
                    put("phone", attMeAddPhone.text.toString())
                    put("imageUrls", "https://img2.baidu.com/it/u=1388480104,566155575&fm=253&fmt=auto&app=120&f=JPEG?w=1422&h=800")
                }.toString().toRequestBody("application/json".toMediaTypeOrNull())).apply {
                    if (this.code == "200"){
                        runOnUiThread {
                            this.msg.show()
                            finish()
                        }
                    }else runOnUiThread {
                        this.code.show()
                        this.msg.show()
                    }
                }

            }else runOnUiThread { "内容不能为空！".show() }
        }
    }





    /**
     * 筛选功能实现
     */
    private suspend fun setOverride() {
        // 发起网络请求获取数据
        Repository.api.getAttMoreAll(App.getToken()).apply {
            if (this.code == 200) {
                runOnUiThread {
                    this.rows?.let { it ->
                        attMeAddMoreRecyclerView.apply {
                            this.layoutManager = GridLayoutManager(context, 2).apply {
                                this.orientation = GridLayoutManager.HORIZONTAL
                            }
                            this.adapter =
                                AttMeAddMoreAllAdapter(ArrayList<AttMoreModel.RowsBean>().apply {
                                    this.addAll(it)
                                }, R.layout.re_att_more)
                        }
                    }

                }
            } else runOnUiThread { this.msg?.show() }
        }
    }


    /**
     * 法律专长列表适配器
     */
    inner class AttMeAddMoreAllAdapter(
        val list: MutableList<AttMoreModel.RowsBean>,
        layoutId: Int
    ) : BaseRecyclerAdapter<AttMoreModel.RowsBean>(list, layoutId) {
        override fun setData(
            view: BaseViewHolder.ViewFind,
            data: AttMoreModel.RowsBean,
            position: Int,
            holder: BaseViewHolder
        ) {
            // 排序
            list.sortByDescending { it.id }

            // 填充数据
            val d = list[position]
            val fv = holder.viewFind

            Util.glide(App.url + d.imgUrl, fv.attMoreImage)
            fv.attMoreTitle.text = d.name

            holder.itemView.setOnClickListener {
                runOnUiThread {
                    idd = d.id
                    attMeAddBtnMore.text = d.name
                }
                attMeAddMoreLayout.visibility = View.GONE
            }
        }
    }

    /**
     * 显示律师信息
     */
    private suspend fun setUserAll(id: Int) {
        val result = Repository.api.getAttUserAll(App.getToken(), id)
        // 填充信息
        if (result.code == 200){
            runOnUiThread {
                result.data?.let { it ->
                    Util.glide(App.url + it.avatarUrl, attListShowImage)
                    attListShowName1.text = it.name
                    attListShowTime1.text = "工作起始时间: ${it.workStartAt}"
                    attListShowSize1.text = "咨询人数: ${it.serviceTimes}人"
                    attListShowYes1.text = "法律专长: ${it.legalExpertiseName}"
                    attListShowAll1.text = "好评率: ${it.favorableCount}%"
                }
            }
        }else runOnUiThread { result.msg?.show() }
    }


    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        finish()
        return super.onOptionsItemSelected(item)
    }
}